#!/bin/sh

[ "$ACTION" = ifup -o "$ACTION" = ifupdate ] || exit 0

interface=lan

enabled="$(uci get fakemesh.default.enabled)"
role="$(uci get fakemesh.default.role)"

[ "$enabled" = "1" ] && [ "$role" != "controller" ] && interface=meshx0

[ "$INTERFACE" = "$interface" ] || exit 0

#change hostname if mesh enabled
if [ "$enabled" = "1" ]; then
	old_hostname="$(uci get system.@system[0].hostname || echo X-WRT)"
	new_hostname="$(uci get network.meshx0.hostname || echo $old_hostname)"
	[ "$old_hostname" != "$new_hostname" ] && {
		uci set system.@system[0].hostname="$new_hostname"
		uci commit system
		/etc/init.d/system reload
		/etc/init.d/umdns running && /etc/init.d/umdns restart
	}
fi
band_steer_helper=$(uci get fakemesh.default.band_steer_helper || echo none)
band_steer_helper="$band_steer_helper" /usr/sbin/fakemesh band_steer_helper_switch

/etc/init.d/umdns enabled && {

[ "$interface" = "meshx0" ] && uci get umdns.@umdns[0] && {
	old_net=$(uci get umdns.@umdns[0].network)
	new_net=$(for net in $old_net meshx0; do echo $net; done | sort | uniq)
	new_net=$(echo $new_net)
#FIXME: since umdns bug, this just an workaroud only
	new_net="meshx0"

	[ "$old_net" != "$new_net" ] && {
		uci delete umdns.@umdns[0].network >/dev/null 2>&1
		for net in $new_net; do
			uci add_list umdns.@umdns[0].network="$net"
		done
		uci commit umdns
		/etc/init.d/umdns reload
	}
	(sleep 60 && /etc/init.d/umdns reload) &
}
[ "$interface" = "lan" ] && uci get umdns.@umdns[0] && {
	old_net=$(uci get umdns.@umdns[0].network)
	new_net=$(for net in $old_net lan; do [ "$net" = "meshx0" ] || echo $net; done | sort | uniq)
	new_net=$(echo $new_net)
	[ "$old_net" != "$new_net" ] && {
		uci delete umdns.@umdns[0].network >/dev/null 2>&1
		for net in $new_net; do
			uci add_list umdns.@umdns[0].network="$net"
		done
		uci commit umdns
		/etc/init.d/umdns reload
	}
	(sleep 60 && /etc/init.d/umdns reload) &
}

} ##/etc/init.d/umdns enabled

uci get usteer.@usteer[0] && {
	old_net=$(uci get usteer.@usteer[0].network)
	new_net="$interface"
	[ "$old_net" != "$new_net" ] && {
		uci set usteer.@usteer[0].network="$new_net"
		uci commit usteer
		[ "$band_steer_helper" = "usteer" ] && /etc/init.d/usteer restart
	}
}

status="$(ubus -S call network.interface.$INTERFACE status)"
[ -n "$status" ] && {
	address=$(echo "$status" | jsonfilter -e '@["ipv4-address"][0].address')
	mask=$(echo "$status" | jsonfilter -e '@["ipv4-address"][0].mask')
	test -n "$address" && test -n "$mask" && {
		broadcast="$(ipcalc.sh "$address/$mask" | grep BROADCAST | cut -d= -f2)"
		uci get dawn.@network[0] && {
			old_broadcast="$(uci get dawn.@network[0].broadcast_ip)"
			[ "$broadcast" = "$old_broadcast" ] || {
				uci set dawn.@network[0].broadcast_ip="$broadcast"
				uci commit dawn
				[ "$band_steer_helper" = "dawn" ] && /etc/init.d/dawn reload
			}
		}
	}
}
